import plugin from '../../lib/plugins/plugin.js'
import common from "../../lib/common/common.js"
import axios from 'axios'

let API_KEY = ''
let SECRET_KEY = ''

let isreview = true  //自动检测总开关
let recall = true  //是否自动撤回
let mute = false  //是否禁言对方
let muteTime = 60  //禁言时长（秒）
let sendurl = true  //是否转发图片直链
let wid = [123, 456]  //需要审核的群

let cs = 30  //手动审核的次数，重启清空
let csmap = new Map()
export class Imagereview extends plugin {
  constructor() {
    super({
            /** 功能名称 */
            name: '图像审核',
            event: 'message',
            /** 优先级，数字越小等级越高 */
            priority: -Infinity,
            rule: [
			    {
		            reg: '.*',
                    fnc: 'autoreview',
			        log: false
                },
                {
				    reg: '^#?图(像|片)审核$',
                    fnc: 'imgreview'
                }
            ]
        })
    }

  async autoreview(e) {
	if (!e.isGroup) return false
	if (!wid.includes(e.group_id) || !isreview) return false
	if (e.img) {
        let imgUrls = []
        imgUrls.push(...e.img)
		for (let img of imgUrls) {
		    let msg = await getdata(img)
			if (!msg) {
			    logger.info(`图像审核请求失败`)
				return false
			}
		    if (msg.conclusion == '不合规') {
				e.reply(`疑似不合规图像（${(msg.data[0].probability).toFixed(2) * 100}%）`, true)
				// 撤回消息
				if (recall) {
				    try {
			    	    let target = e.isGroup ? e.group : e.friend
                        await target.recallMsg(e.message_id)
					    logger.info(`${e.group_id}→${e.user_id}执行撤回消息`)
				    } catch(error) {
					    e.reply(`执行撤回消息失败`)
				    }
				}
				// 禁言对方
				if (mute) {
				    if (e.isGroup) {
					    try {
					    	await e.group.muteMember(e.user_id, muteTime)
						    logger.info(`${e.group_id}→${e.user_id}执行禁言`)
					    } catch(error) {}
					}
				}	
				if (sendurl) {
				    let wgmsg = `疑似${e.sender.card || e.sender.nickname}[${e.user_id}]发送的违规图片：\n\n${img}`
	   		        await e.reply(await common.makeForwardMsg(e,wgmsg))
				}
				return true
			} 
			else if (msg.conclusion == '疑似') {
				e.reply(`疑似擦边图像（${(msg.data[0].probability).toFixed(2) * 100}%）`, true)
			} 
			else {
				logger.info(msg.conclusion)
			}
	    }
	}
	return false
  }

  async imgreview(e) {
	let imageUrl = await this.getImage(e)
	if (!imageUrl) return
	if (!csmap[e.group_id]) {
		csmap[e.group_id] = 0
	}
	if (csmap[e.group_id] >= cs) {
		e.reply(`手动审核次数已达上限`,true,{ recallMsg: 10 })
		return true
	}
	// 如果 imageUrl 条数大于 5，只取前 5 条
    if (imageUrl.length > 5) {
        imageUrl = imageUrl.slice(0, 5);
    }
	let msgs = []
	
	for (let img of imageUrl) {
		let msg = await getdata(img)
		if (!msg) return e.reply(`请求失败`)
		let num = msg.data ? `（${(msg.data[0].probability).toFixed(2) * 100}%）` : ``
		msgs.push(`${msg.conclusion}${num}`)
		csmap[e.group_id] ++
	}
	if (imageUrl.length > 1) {
	    await e.reply(`共识别到${imageUrl.length}张图片，本次结果为：\n${msgs.join('，')}`, true)
	} else {
		await e.reply(msgs, true)
	}
  }
  
  async getImage(e) {
	let imgUrls = []
	  if (e.source || e.reply_id ) {
        // 优先从回复找图
        let reply
        if (this.e.getReply) {
          reply = await this.e.getReply()
        } else if (this.e.source) {
          if (this.e.group?.getChatHistory)
            reply = (await this.e.group.getChatHistory(this.e.source.seq, 1)).pop()
          else if (this.e.friend?.getChatHistory)
            reply = (await this.e.friend.getChatHistory(this.e.source.time, 1)).pop()
        }
        if (reply?.message) {
          for (let val of reply.message) {
            if (val.type === 'image') {
                imgUrls.push(val.url)
            }
          }
        }
      }
	  else if (e.img) {
        // 一起发的图
        imgUrls.push(...e.img)
      }   
	if (imgUrls.length > 0) {
        return imgUrls
	} else {
		return ''
	}
  }
}

async function getdata(imageUrl) {
	let base64 = await url_to_base64(imageUrl)
	try {
	    const accessToken = await getAccessToken();
        const url = `https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined?access_token=${accessToken}`;
        const params = {
            image: base64
        };
        const headers = {
            'Content-Type': 'application/x-www-form-urlencoded'
        };
        const response = await axios.post(url, new URLSearchParams(params), { headers });
	    return response.data
	} catch(error) {
		return ''
	}
  }
  	
export { getdata };  //给其它插件调用 import { getdata } from './Imagereview.js';

async function url_to_base64(url) {
        let img = await axios.get(url, {
            responseType: 'arraybuffer'
        });
        let base64 = Buffer.from(img.data, 'binary')
            .toString('base64');
        return base64
    }
	
// 获取Access Token
async function getAccessToken() {
    const url = `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${API_KEY}&client_secret=${SECRET_KEY}`;
    const response = await axios.post(url);
    return response.data.access_token;
}